package com.gvsoft.communication.net;

import com.gvsoft.communication.net.model.IPacket;
import com.gvsoft.communication.net.packethandle.IPacketHandle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.channels.SelectionKey;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/9/7
 * Time: 下午3:38
 * Desc: 报文处理线程
 */
public class PacketHandleThread implements Runnable {
    private IPacket iPacket;
    private SelectionKey key;
    private Dispatcher dispatcher;
    private final static Logger logger = LogManager.getLogger("net");

    public PacketHandleThread(IPacket iPacket, SelectionKey key,Dispatcher dispatcher) {
        this.iPacket = iPacket;
        this.key = key;
        this.dispatcher = dispatcher;
    }

    public void run() {

        NSocket nSocket = (NSocket) key.attachment();
        IPacketHandle handle = dispatcher.getPacketHandleInstance(iPacket.getHeader());

        if (null != handle){
            nSocket.setLastAccessTime((int) System.currentTimeMillis());
            handle.handlePacket(iPacket, nSocket);
        }else{
            //不在服务端识别范围内的报文，回复E响应，告知客户端不合法
            //ErrorOrder errorOrder = new ErrorOrder(ErrorOrder.INVAILD_REQ_CODE, ErrorOrder.INVAILD_REQ_MSG);
            //nSocket.write(errorOrder);
            logger.error("收到无法识别消息格式,丢弃!");
        }
    }

}
